package com.ydj.app.config.interceptor;

import com.ydj.app.WebConst;
import com.ydj.app.protocol.redis.RdsWebLoginInfo;
import com.ydj.framework.exception.VerifyTokenException;
import com.ydj.framework.filter.ExtHttpServletRequest;
import com.ydj.framework.filter.ExtHttpServletResponse;
import com.ydj.framework.interceptor.AuthBaseInterceptor;
import com.ydj.framework.redis.ExtRedisTemplate;
import com.ydj.framework.redis.RedisKey;
import org.apache.logging.log4j.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 小程序的拦截器
 */
@Component
public class WebUserAuthInterceptor extends AuthBaseInterceptor {
    @Autowired
    private ExtRedisTemplate redisTemplate;

    @Autowired
    private WebConst mpConst;

    @Override
    public String getPathPatterns() {
        return mpConst.getBaseUrl() + "/**";
    }

    @Override
    public boolean doPreHandle(ExtHttpServletRequest request, ExtHttpServletResponse response, Object handler, String token) throws VerifyTokenException {
        String key = RedisKey.getWebToken(token);
        RdsWebLoginInfo rdsInfo = redisTemplate.getIfExceptionDelete(key);

        // 从 Redis 中读取到的是错误格式，让前端重新走一次登录流程
        if (rdsInfo == null) {
            throw new VerifyTokenException();
        }

        Long userId = rdsInfo.getWebUserId();
        if (userId == null) {
            redisTemplate.delete(key);
            throw new VerifyTokenException();
        }
        ThreadContext.put("userId", rdsInfo.getIdForLog());

        // 续期 token
        redisTemplate.expire(key, 7, TimeUnit.DAYS);
        request.getInterceptorContext().setRdsLoginInfo(rdsInfo);
        return true;
    }
}